import React, { memo, useEffect, useRef, useState } from 'react';
import { withRouter } from 'react-router-dom';
import { Button, Modal, Input, Select } from 'antd';
import { useDispatch } from 'react-redux';

import './style.less';
import { addPersonAction } from './store/actionCreators';

export default withRouter(
  memo(function AddModal(props) {
    const canAdd = useRef();
    useEffect(() => {
      if (props.location.pathname !== '/main/user') {
        canAdd.current.disabled = true;
      }
    });
    const { Option } = Select;
    const [isModalVisible, setIsModalVisible] = useState(false);
    const dispatch = useDispatch();
    const person = {
      name: '',
      realname: '',
      password: '',
      cellphone: '',
    };

    const showModal = () => {
      setIsModalVisible(true);
    };

    const handleOk = () => {
      setIsModalVisible(false);
      dispatch(addPersonAction(person));
    };

    const handleCancel = () => {
      setIsModalVisible(false);
    };

    const roleChange = (value) => {
      person.roleId = value;
    };

    const depatmentChange = (value) => {
      person.departmentId = value;
    };

    const getName = (e) => {
      person.name = e.target.value;
    };

    const getRelName = (e) => {
      person.realname = e.target.value;
    };

    const getPassword = (e) => {
      person.password = e.target.value;
    };

    const getTell = (e) => {
      person.cellphone = e.target.value;
    };

    useEffect(() => {}, []);

    return (
      <div className="add-modal">
        <Button type="primary" onClick={showModal} ref={canAdd}>
          新增
        </Button>
        <Modal
          title="增加用户"
          visible={isModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <p>
            用户名：
            <Input onBlur={getName} />
          </p>
          <p>
            真实姓名：
            <Input onBlur={getRelName} />
          </p>
          <p>
            密码：
            <Input type="password" onBlur={getPassword} />
          </p>
          <p>
            电话号码：
            <Input type="tel" onBlur={getTell} />
          </p>
          <p>
            选择角色：
            <Select style={{ width: 472 }} onChange={roleChange}>
              <Option value="0" disabled>
                ceo
              </Option>
              <Option value="1">人事</Option>
              <Option value="2">运营</Option>
              <Option value="3">超级管理员</Option>
            </Select>
          </p>
          <p>
            选择部门：
            <Select style={{ width: 472 }} onChange={depatmentChange}>
              <Option value="0">人事部</Option>
              <Option value="1">客服部</Option>
              <Option value="2">运营部</Option>
              <Option value="3">研发部</Option>
              <Option value="4">总督办</Option>
            </Select>
          </p>
        </Modal>
      </div>
    );
  }),
);
